package com.only4play.portal.cp.bean.message.jsonmessage;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.only4play.portal.cp.bean.message.AbstractCpMessage;
import com.only4play.portal.cp.config.CpConfigStorage;
import com.only4play.portal.cp.util.crypto.CpCryptUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

@Slf4j
@Getter
@Setter
public class CpJsonMessage extends AbstractCpMessage {

    private String agentId;

    private String fromUserName;

    private String toUserName;

    private Long createAt;

    private String msgType;

    private String content;

    private Long msgId;

    private String event;

    private String eventKey;

    private String changeType;

    public static CpJsonMessage fromEncryptedJson(
        String encryptedData,
        CpConfigStorage cpConfigStorage,
        String timestamp,
        String nonce,
        String msgSignature
    ) {
        CpCryptUtil cpCryptUtil = new CpCryptUtil(cpConfigStorage);

        CpJsonMessage cpJsonMessage = fromJson(encryptedData);
        String plainText = cpCryptUtil.decrypt(msgSignature, timestamp, nonce, encryptedData);
        String msgAgentId = cpJsonMessage.getAgentId();
        if (StringUtils.isNotBlank(msgAgentId)) {
            return fromJson(plainText, msgAgentId);
        } else {
            return fromJson(plainText);
        }
    }

    protected static CpJsonMessage fromJson(String json, String agentId) {
        final CpJsonMessage cpJsonMessage = fromJson(json);
        cpJsonMessage.setAgentId(agentId);
        return cpJsonMessage;
    }

    protected static CpJsonMessage fromJson(String json) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(json, new TypeReference<>() {
            });
        } catch (Exception exception) {
            return new CpJsonMessage();
        }
    }

}
